# -*- coding: utf-8 -*-
import datetime
import logging
import os.path
import shutil
from threading import Thread, Event, current_thread
from job import upload_oss
from job.generate_video import GenerateVideo
from pkg.utils.file_urtils import create_folder, create_time_str
from job.merge_video import merge_video_and_audio, convert_mov
from job.generate_audio import text2audio
from tinytag import TinyTag
from settings import MAX_RETRY, VIDEO_SAVE_API_URL, VIDEO_DETAIL_URL, VIDEO_PUSH_MESSAGE_URL
from pkg.comm.global_request_api import save_job_api, save_video_detail,push_message
import time
logger = logging.getLogger(__name__)

STATIC_BASE_PATH = r"static\output"
TMP_PATH = r"static\tmp"
GENERIC_PATH = r'E:\images\generic_image'


def run(job_id, worker_ip, text, embedding, embed_time, init_datas):
    begin = time.time()
    save_job_api(VIDEO_SAVE_API_URL, job_id,worker_ip, status='in_progress')
    folder = create_time_str()
    output_folder = create_folder(STATIC_BASE_PATH, folder)
    tmp_folder = create_folder(TMP_PATH, folder)
    # 这些都放临时目录
    mp3_out_file_tmp = os.path.join(tmp_folder, 'audio.mp3')
    srt_out_file_tmp = os.path.join(tmp_folder, 'subtitles.srt')
    mute_out_file_tmp = os.path.join(tmp_folder, 'mute_video.mp4')

    # 这个最终成品
    out_file_watermark = None
    file_name = str(datetime.datetime.now().timestamp()).split('.')[0]
    out_file = os.path.join(output_folder, file_name + '.mp4')
    out_mov_file = os.path.join(output_folder, file_name + '.mov')


    subtitle_font_size = 30
    video_size = (1200, 780)
    line_words = int((video_size[0] * 0.9) / subtitle_font_size)


    # 文字生成音频和字幕
    t1 = time.time()
    try:
        text2audio(text, mp3_out_file_tmp, srt_out_file_tmp, line_words)
        t2 = time.time()
        audio_t = t2 - t1
        audio_t = int(audio_t * 100) / 100
        save_video_detail(VIDEO_DETAIL_URL, job_id,worker_ip, embed_seconds=embed_time, audio_seconds=audio_t,mark='文字生成音频和字幕过程', status='in_progress')
    except Exception as e:
        save_video_detail(VIDEO_DETAIL_URL, job_id, worker_ip, embed_seconds=embed_time, audio_seconds=0,mark='音频和字幕,生成失败', status='failed')
        return None, None, None, None

    # 解析文件头部信息
    audio = TinyTag.get(mp3_out_file_tmp)
    fps = 24
    # 计算时长
    duration = audio.duration + 3
    nframes = int(duration * fps)

    t3 = time.time()
    try:
        generator = GenerateVideo()
        # 图片生成视频
        # generator.gen_mute_image_video_embedding(mute_out_file_tmp, video_size, embedding, duration, fps)
        # 视频生成视频
        generator.gen_mute_video_video_embedding(mute_out_file_tmp, embedding, duration, fps)
        t4 = time.time()
        video_t = t4 - t3
        video_t = int(video_t*100)/100
        save_video_detail(VIDEO_DETAIL_URL, job_id, worker_ip, embed_seconds=embed_time, audio_seconds=audio_t,video_seconds=video_t, mark='生成视频过程', status='in_progress')
    except Exception as e:
        save_video_detail(VIDEO_DETAIL_URL, job_id, worker_ip, embed_seconds=embed_time, audio_seconds=audio_t,video_seconds=0,mark='生成视频,失败', status='failed')
        return None, None, None, None

    # 合并音频和视频
    t5 = time.time()
    try:
        output_image_path = merge_video_and_audio(mute_out_file_tmp, mp3_out_file_tmp, srt_out_file_tmp, out_file,output_watermark=out_file_watermark, font='black.ttf', font_size=subtitle_font_size)
        end = time.time()
        merge_t = end - t5
        merge_t = int(merge_t * 100) / 100
        consume_second = end - begin
        consume_second = int(consume_second * 100) / 100
        save_video_detail(VIDEO_DETAIL_URL, job_id, worker_ip, embed_seconds=embed_time, audio_seconds=audio_t,video_seconds=video_t, consume_seconds=consume_second, merge_seconds=merge_t,status='in_progress')
    except Exception as e:
        save_video_detail(VIDEO_DETAIL_URL, job_id, worker_ip, embed_seconds=embed_time, audio_seconds=audio_t,video_seconds=video_t, consume_seconds=0, merge_seconds=0,mark='合并视频,失败', status='failed')
        return None, None, None, None

    # 转换mp4为mov格式
    convert_mov(out_file, out_mov_file)


    try:
        cover_url = upload_oss.upload_file_oss(output_image_path)
        url = upload_oss.upload_file_oss(out_mov_file)
        save_video_detail(VIDEO_DETAIL_URL, job_id, worker_ip, embed_seconds=embed_time, audio_seconds=audio_t,video_seconds=video_t, consume_seconds=consume_second, merge_seconds=merge_t,status='in_progress')
    except Exception as e:
        save_video_detail(VIDEO_DETAIL_URL, job_id, worker_ip, embed_seconds=embed_time, audio_seconds=audio_t,video_seconds=video_t, consume_seconds=consume_second, merge_seconds=merge_t, mark='oss上传视频链接,失败',status='failed')
        return None, None, None, None


    user_id = init_datas.get('user_id', None)
    push_result = push_message(VIDEO_PUSH_MESSAGE_URL, user_id)
    if push_result:
        push_mark = '推送推送失败'+push_result
        save_video_detail(VIDEO_DETAIL_URL, job_id, worker_ip, embed_seconds=embed_time, audio_seconds=audio_t,
                          video_seconds=video_t, consume_seconds=consume_second, merge_seconds=merge_t,
                          mark=push_mark, status='failed')
        return None, None, None, cover_url
    save_video_detail(VIDEO_DETAIL_URL, job_id, worker_ip, embed_seconds=embed_time, audio_seconds=audio_t,
                      video_seconds=video_t, consume_seconds=consume_second, merge_seconds=merge_t, status='completed')
    # 删除临时文件
    shutil.rmtree(tmp_folder)
    shutil.rmtree(output_folder)
    return consume_second, url, duration, cover_url

